/*
 * ServerUserBaseImpl.java
 *
 * Created on 2009�?�?4�? 下午10:36
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package com.erp.server;

import com.erp.server.DB.DbConn;
import com.erp.client.DAO.Customer;
import com.erp.client.DAO.FileInfo;
import com.erp.client.DAO.RzLogFind;
import com.erp.client.DAO.SeriaRzLog;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.erp.client.DAO.ServerUserBase;
import com.erp.client.DAO.UserBaseInf;
import com.erp.client.DAO.UserPasswordChange;
import com.erp.client.Stock1;
import com.erp.server.BPO.UserBPO;
import com.erp.server.DAO.FileDao;
import com.erp.server.DAO.RzDao;
import com.google.gwt.core.ext.typeinfo.ParseException;
import com.google.gwt.i18n.client.DateTimeFormat;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *
 * @author Administrator
 */
public class ServerUserBaseImpl extends RemoteServiceServlet implements
        ServerUserBase {

    //private SeriaRzLog seriarzlog;
    private UserBaseInf ub;
    
    public UserBaseInf getUb() {
        return ub;
    }

    public void setUb(UserBaseInf ub) {
        this.ub = ub;
    }

    //用户信息和权限操作
//********************************************************************
    public String UserRightsLogin(UserBaseInf ub) {
        //完成用户的登录验证，不返回任何值，直接将信息写入session,
        //loginstate = 0 登录失败
        //loginstate = １ 登录成功
        //session中empuser字段存储用户信息
        Integer loginstate;
        loginstate = 0;
        UserBPO userbpo = new UserBPO();
        HttpServletRequest request = this.getThreadLocalRequest();
        HttpSession session = request.getSession();
        
        //HttpServletRequest request = this.getThreadLocalRequest();
        //HttpSession session =request.getSession();
        if (userbpo.check(ub)) {
            loginstate = 1;
            setUb(userbpo.getUb());
            session.setAttribute("loginstate", loginstate);
            session.setAttribute("empuser", getUb());
            
            return "Success";
        } else {
            session.setAttribute("loginstate", loginstate);
            
            return "Failure";
        }
    }

    public List<UserBaseInf> UserRightsGet() {
        //取回用户的登录验证,返回List<UserBaseInf>
        //loginstate = 0 登录失败
        //loginstate = １ 登录成功
        //session中empuser字段存储用户信息
        List<UserBaseInf> userbaseinf = new ArrayList<UserBaseInf>();
        HttpServletRequest request = this.getThreadLocalRequest();
        HttpSession session = request.getSession();
        UserBaseInf tempuserbaseinf = new UserBaseInf();
        tempuserbaseinf = (UserBaseInf) session.getAttribute("empuser");
        userbaseinf.add(tempuserbaseinf);
        return userbaseinf;
    }

    public String userchangepassword(UserPasswordChange ub){
        
        UserBPO userbpo = new UserBPO();
        
         if (userbpo.changePassword(ub)) {
            return "Success";
        } else {
            return "Failure";
        }
    }
//********************************************************************
    public List<SeriaRzLog> getRzlogByDate(RzLogFind rzlogfind) {
        List<SeriaRzLog> rzlog = new ArrayList<SeriaRzLog>();

        RzDao rzlogreturn = new RzDao();
        try {
            rzlog = rzlogreturn.getRzlogByDate(rzlogfind);
        } catch (SQLException ex) {
            Logger.getLogger(ServerUserBaseImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rzlog;
    }

    public List<SeriaRzLog> getRzlogByrzid(int userid) {
        List<SeriaRzLog> rzlog = new ArrayList<SeriaRzLog>();

        RzDao rzlogreturn = new RzDao();
        try {
            rzlog = rzlogreturn.getRzlogByrzid(userid);
        } catch (SQLException ex) {
            Logger.getLogger(ServerUserBaseImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rzlog;
    }

    public List<SeriaRzLog> getRzlogAll() {
        List<SeriaRzLog> rzlog = new ArrayList<SeriaRzLog>();
        RzDao rzlogreturn = new RzDao();
        try {
            rzlog = rzlogreturn.getRzlogAll();
        } catch (SQLException ex) {
            Logger.getLogger(ServerUserBaseImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rzlog;
    }

    public String SaveRzlog(SeriaRzLog seriarzlog) {
        String returnString = "操作失败";
        //DbConn dc = new DbConn();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s;
        String sql = "INSERT INTO RzLog(EmpID,EmpName,DepID,DepName,RecDate,Week,BeginTime,EndTime,recData,InputDate) VALUES (" + "?,?,?,?,?,?,?,?,?,?)";//,MangeID,MangeDemo,MangeNumerical
        Connection conn = DbConn.getCon();
        
        // conn = dc.getConn_jdbc();
        returnString = "操作成功";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, seriarzlog.getEmpId());
            ps.setString(2, seriarzlog.getEmpName());
            ps.setInt(3, seriarzlog.getDepId());
            ps.setString(4, seriarzlog.getDepName());            
            s = df.format(seriarzlog.getRecDate());
            ps.setString(5, s);            
            ps.setString(6, getDayOfWeek(seriarzlog.getRecDate()));
            ps.setString(7, seriarzlog.getBeginTime());
            ps.setString(8, seriarzlog.getEndTime());
            ps.setString(9, seriarzlog.getRecData());
            s = df.format(new Date());
            ps.setString(10, s);
            /*ps.setInt(11, seriarzlog.getMangeId());
            ps.setString(12, seriarzlog.getMangeDemo());
            ps.setDouble(13, seriarzlog.getMangeNumerical());*/
            ps.executeUpdate();
            returnString = "操作成功";
            return returnString;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            returnString = "操作失败" + e.getMessage();
            return returnString;
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ServerUserBaseImpl.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    //JSONArray jsonobject = JSONArray.fromObject(userbaseinf);


    }

    public String UpdataRzlog(SeriaRzLog seriarzlog) {
        String returnString = "操作失败";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s;
        //DbConn dc = new DbConn();
        String sql = "UPDATE RzLog SET recData =?,inputDate=? " + "  WHERE rzID=? and MangeDemo IS NULL";
        //System.out.print(sql);
        //Connection conn = DbConn.getConn_jdbc();
        //conn = dc.getConn_jdbc();
        Connection conn = DbConn.getCon();

        try {
            /*Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(strSql);*/
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, seriarzlog.getRecData());
            s = df.format(new Date());
            ps.setString(2, s);
            ps.setInt(3, seriarzlog.getRzId());
            ps.executeUpdate();
            conn.close();
            returnString = "操作成功";
            return returnString;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //dc.CloseConn();
            returnString = "操作失败" + e.getMessage();
            return returnString;
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ServerUserBaseImpl.class.getName()).log(Level.SEVERE, null, ex);
                returnString = "操作失败";
                return returnString;
            }

        }

    }
//*********************************************************************************

    public List<Customer> getCustomers() {
        List<Customer> customers = new ArrayList<Customer>();
        customers.add(new Customer("Darrell", "darrell@foo.com", 1));
        customers.add(new Customer("Maro", "maro@foo.com", 2));
        customers.add(new Customer("Alec", "alec@foo.com", 3));
        customers.add(new Customer("Lia", "lia@foo.com", 4));
        return customers;
    }

    public List<Customer> mygetCustomers() {
        List<Customer> customers = new ArrayList<Customer>();
        customers.add(new Customer("搞定了么？", "darrell@foo.com", 1));
        customers.add(new Customer("Maro", "maro@foo.com", 2));
        customers.add(new Customer("Alec", "alec@foo.com", 3));
        customers.add(new Customer("搞定了", "lia@foo.com", 1114));
        return customers;
    }

//*********************************************************************************
//*********************************************************************************
    public String getTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    public String getDayOfWeek(Date date) {
        SimpleDateFormat getdf = new SimpleDateFormat("yyyyMMdd");
        String argDate = getdf.format(date);

        //s = df.format(argDate);
         if   (argDate.length()   !=   8)   {
              throw   new   IllegalArgumentException("argDate   length   !=   8");
          }

          int   intArgY   =   Integer.parseInt(argDate.substring(0,   4));
          int   intArgM   =   Integer.parseInt(argDate.substring(4,   6))   -   1;
          int   intArgD   =   Integer.parseInt(argDate.substring(6));

          Calendar   calendar   =   GregorianCalendar.getInstance();
          calendar.set(intArgY,   intArgM,   intArgD);

          int   returnDayOfWeek   =   calendar.get(Calendar.DAY_OF_WEEK);

        String showDate = "";
        switch (returnDayOfWeek) {
            case 1:
                showDate = "星期日";
                break;
            case 2:
                showDate = "星期一";
                break;
            case 3:
                showDate = "星期二";
                break;
            case 4:
                showDate = "星期三";
                break;
            case 5:
                showDate = "星期四";
                break;
            case 6:
                showDate = "星期五";
                break;
            default:
                showDate = "星期六";
                break;
        }


        return showDate;
    }
//****************************************************************************
//文件操作
public List<FileInfo> getFileByID(int empid) {
        System.out.print(" filedao-EmpID :"+empid);

        List<FileInfo> fileall = new ArrayList<FileInfo>();
        FileDao filereturn = new FileDao();
        try {
            fileall = filereturn.getFileByEmpid(empid);
        } catch (SQLException ex) {
            Logger.getLogger(ServerUserBaseImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return fileall;
    }
//****************************************************************************
//****************************************************************************
    public String rzls() {
        String testls = "";
        SeriaRzLog rzlog = new SeriaRzLog();
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray jsonarray = new JSONArray();
        JSONObject jsonobject = new JSONObject();
        //Connection conn;
        DbConn dc = new DbConn();
        String strSql = "select * from rzlog ";//where LoginID='tt'";
        Connection conn = DbConn.getCon();
        conn = dc.getConn_jdbc();
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(strSql);
            //[{"depId":2,"empId":1,"inputDate":null,"mangeDemo":"","mangeId":0,"mangeNumerical":0,"recData":"","recDate":null,"rzId":0}]
            while (rs.next()) {
                rzlog.setDepId(rs.getInt("depId"));
                rzlog.setEmpId(rs.getInt("empId"));
                rzlog.setEmpName(rs.getString("EmpName"));
                rzlog.setRecData(rs.getString("recData"));
                rzlog.setMangeDemo(rs.getString("mangeDemo"));
                rzlog.setMangeId(rs.getInt("mangeId"));
                rzlog.setMangeNumerical(rs.getInt("mangeNumerical"));
                rzlog.setInputDate(rs.getDate("inputDate"));
                rzlog.setRecDate(rs.getDate("recDate"));
                rzlog.setRzId(rs.getInt("rzId"));
                jsonarray.add(rzlog);
            }
            rs.close();
            dc.CloseConn();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            dc.CloseConn();
        }
        //JSONArray jsonobject = JSONArray.fromObject(userbaseinf);
        System.out.println(jsonobject);
        //testls = jsonobject;//.toString();
        jsonobject = jsonarray.toJSONObject(jsonarray);
        return jsonobject.toString();//jsonarray.toString();
    }

    public String myMethod(String s) {
        // Do something interesting with 's' here on the server.
        return "Server says: " + s;
    }

    public String myTest(String s) {
        // Do something interesting with 's' here on the server.
        String stringflag = "测试失败了";
        Connection conn;
        DbConn dc = new DbConn();

        String strSql = "select * from userBaseInf where LoginID='" + s + "'";
        if ((s.trim()) == "") {
            strSql = "select * from userBaseInf where LoginID='tt'";
        } else {
            strSql = "select * from userBaseInf where LoginID='" + s + "'";
        }
        //Connection conn = DbConn.getCon();
        conn = dc.getConn_jdbc();
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(strSql);
            while (rs.next()) {
                stringflag = rs.getString("userName");
            }
            rs.close();
            dc.CloseConn();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            stringflag = "ERROR";
            e.printStackTrace();
        } finally {
            dc.CloseConn();
        }

        System.out.println("userDaoImpl" + stringflag);
        return stringflag;

    }

    public String ls() {
        String testls = "";
        UserBaseInf userbaseinf = new UserBaseInf();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray jsonobject = new JSONArray();

        //Connection conn;
        DbConn dc = new DbConn();
        String strSql = "select * from userBaseInf ";//where LoginID='tt'";
        Connection conn = DbConn.getCon();
        conn = dc.getConn_jdbc();
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(strSql);

            while (rs.next()) {
                userbaseinf.setLoginId(rs.getString("loginId"));
                userbaseinf.setUserName(rs.getString("userName"));
                userbaseinf.setPassword(rs.getString("password"));
                userbaseinf.setUserId(rs.getInt("userId"));
                //userbaseinf.setLockDate(rs.getDate("lockDate"));
                //mangeright.add(userbaseinf);
                //userbaseinf=null;
                jsonobject.add(userbaseinf);
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            dc.CloseConn();
        }
        //JSONArray jsonobject = JSONArray.fromObject(userbaseinf);
        System.out.println(jsonobject);
        testls = jsonobject.toString();

        return testls;
    }

    public List<Stock1> testarray() {
        //List<RzlogStore> stocks = new ArrayList<RzlogStore>();
        DateTimeFormat f = DateTimeFormat.getFormat("M/d h:mma");
        List<Stock1> stocks = new ArrayList<Stock1>();


        stocks.add(new Stock1("3m Co", 71.72, 0.02, 0.03, f.parse("4/2 12:00am"), "Manufacturing"));
        stocks.add(new Stock1("Alcoa Inc", 29.01, 0.42, 1.47, f.parse("4/1 12:00am"), "Manufacturing"));


        System.out.println(stocks);
        JSONArray jsonArray = JSONArray.fromObject(stocks);
        System.out.println(jsonArray);
        return stocks;
    }
}


